#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
自动审核服务API测试脚本
用法: python api_test.py [--url http://localhost:8090]
"""

import argparse
import json
import logging
import requests
import sys
import time
from typing import Dict, Any, List, Optional

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger("api-test")

class AuditServiceTester:
    """审核服务API测试工具"""
    
    def __init__(self, base_url: str = "http://localhost:8090"):
        """初始化测试工具
        
        Args:
            base_url: API基础URL
        """
        self.base_url = base_url
        logger.info(f"初始化测试工具，API地址: {base_url}")
    
    def check_health(self) -> bool:
        """检查服务健康状态"""
        url = f"{self.base_url}/health"
        logger.info(f"测试健康检查接口: {url}")
        
        try:
            response = requests.get(url, timeout=5)
            logger.info(f"响应状态码: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                logger.info(f"服务状态: {result.get('status', 'unknown')}")
                return True
            else:
                logger.error(f"健康检查失败: {response.text}")
                return False
        except Exception as e:
            logger.error(f"健康检查请求异常: {str(e)}")
            return False
    
    def test_audit_api(self, test_cases: List[Dict[str, Any]]) -> bool:
        """测试内容审核API
        
        Args:
            test_cases: 测试用例列表
        
        Returns:
            bool: 所有测试是否通过
        """
        url = f"{self.base_url}/api/audit"
        logger.info(f"测试审核API: {url}")
        
        all_passed = True
        for idx, case in enumerate(test_cases, 1):
            logger.info(f"\n测试用例 #{idx}: {case.get('description', '未命名用例')}")
            
            # 准备请求数据
            request_data = {
                "post_id": case.get("post_id", 1000 + idx),
                "title": case.get("title", "测试标题"),
                "content": case.get("content", "测试内容"),
                "user_id": case.get("user_id", 1),
                "category": case.get("category"),
                "tags": case.get("tags")
            }
            
            logger.info(f"请求数据: {json.dumps(request_data, ensure_ascii=False)}")
            
            try:
                # 发送请求
                response = requests.post(url, json=request_data, timeout=10)
                logger.info(f"响应状态码: {response.status_code}")
                
                if response.status_code == 200:
                    result = response.json()
                    self._pretty_print_audit_result(result)
                    
                    # 验证结果
                    expected_result = case.get("expected_result")
                    if expected_result:
                        passed = self._verify_audit_result(result, expected_result)
                        if not passed:
                            all_passed = False
                            logger.error("测试用例未通过 ✗")
                        else:
                            logger.info("测试用例通过 ✓")
                    else:
                        logger.info("没有预期结果，跳过验证")
                else:
                    logger.error(f"请求失败: {response.text}")
                    all_passed = False
            except Exception as e:
                logger.error(f"请求异常: {str(e)}")
                all_passed = False
            
            logger.info("-" * 50)
        
        return all_passed
    
    def test_feedback_api(self, feedback_data: Dict[str, Any]) -> bool:
        """测试反馈API
        
        Args:
            feedback_data: 反馈数据
        
        Returns:
            bool: 测试是否通过
        """
        url = f"{self.base_url}/api/feedback"
        logger.info(f"\n测试反馈API: {url}")
        
        # 准备请求数据
        request_data = {
            "post_id": feedback_data.get("post_id", 1001),
            "admin_id": feedback_data.get("admin_id", 999),
            "ai_decision": feedback_data.get("ai_decision", "REVIEW"),
            "final_decision": feedback_data.get("final_decision", "PASS"),
            "is_correct": feedback_data.get("is_correct", False),
            "feedback": feedback_data.get("feedback", "测试反馈")
        }
        
        logger.info(f"请求数据: {json.dumps(request_data, ensure_ascii=False)}")
        
        try:
            # 发送请求
            response = requests.post(url, json=request_data, timeout=10)
            logger.info(f"响应状态码: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                logger.info(f"响应结果: {json.dumps(result, ensure_ascii=False)}")
                
                # 验证结果
                if result.get("status") == "success":
                    logger.info("反馈测试通过 ✓")
                    return True
                else:
                    logger.error("反馈测试未通过 ✗")
                    return False
            else:
                logger.error(f"请求失败: {response.text}")
                return False
        except Exception as e:
            logger.error(f"请求异常: {str(e)}")
            return False
    
    def _pretty_print_audit_result(self, result: Dict[str, Any]) -> None:
        """美化打印审核结果"""
        audit_result = result.get("audit_result", "UNKNOWN")
        confidence = result.get("confidence", 0.0)
        reasons = result.get("reasons", [])
        suggestion = result.get("suggestion", "")
        
        logger.info(f"响应结果:")
        logger.info(f"- 审核结果: {audit_result}")
        logger.info(f"- 置信度: {confidence:.2f}")
        
        if reasons:
            logger.info("- 原因:")
            for i, reason in enumerate(reasons, 1):
                logger.info(f"  {i}. {reason}")
        else:
            logger.info("- 原因: 无")
        
        logger.info(f"- 建议: {suggestion}")
    
    def _verify_audit_result(self, actual: Dict[str, Any], expected: Dict[str, Any]) -> bool:
        """验证审核结果是否符合预期
        
        Args:
            actual: 实际结果
            expected: 预期结果
        
        Returns:
            bool: 是否通过验证
        """
        # 检查审核结果
        if "audit_result" in expected and actual.get("audit_result") != expected["audit_result"]:
            logger.error(f"审核结果不匹配: 期望 {expected['audit_result']}, 实际 {actual.get('audit_result')}")
            return False
        
        # 检查置信度
        if "confidence_min" in expected and actual.get("confidence", 0) < expected["confidence_min"]:
            logger.error(f"置信度过低: 期望至少 {expected['confidence_min']}, 实际 {actual.get('confidence')}")
            return False
        
        # 检查原因中是否包含特定关键词
        if "reason_keywords" in expected:
            reasons = " ".join(actual.get("reasons", []))
            for keyword in expected["reason_keywords"]:
                if keyword not in reasons:
                    logger.error(f"原因中未包含关键词: {keyword}")
                    return False
        
        return True

def get_test_cases() -> List[Dict[str, Any]]:
    """获取测试用例"""
    return [
        {
            "description": "正常内容测试",
            "post_id": 1001,
            "title": "讨论一下Python的优缺点",
            "content": "Python是一种非常流行的编程语言，它的优点是语法简洁，易于学习，生态系统丰富。但也有性能相对较慢的缺点。想听听大家的看法。",
            "user_id": 1,
            "expected_result": {
                "audit_result": "PASS",
                "confidence_min": 0.7
            }
        },
        {
            "description": "垃圾广告内容测试",
            "post_id": 1002,
            "title": "赚钱好方法",
            "content": "想要赚钱吗？快来加入我们的项目！添加微信号123456获取详情，月入过万不是梦！http://money.make.com?r=27483",
            "user_id": 2,
            "expected_result": {
                "audit_result": "REJECT",
                "confidence_min": 0.8,
                "reason_keywords": ["广告", "联系方式", "链接"]
            }
        },
        {
            "description": "负面情绪内容测试",
            "post_id": 1003,
            "title": "对这个软件非常失望",
            "content": "这是我用过的最差的软件，完全是垃圾，开发者就是一群骗子，骗我的钱，害我浪费了很多时间！太恶心了！",
            "user_id": 3,
            "category": "反馈",
            "expected_result": {
                "audit_result": "REVIEW",
                "reason_keywords": ["负面", "情绪"]
            }
        },
        {
            "description": "敏感词内容测试",
            "post_id": 1004,
            "title": "讨论一下当前形势",
            "content": "最近看到一些赌博网站的广告，这些都是非法的吧？还有贩卖毒品的，很可怕。",
            "user_id": 4,
            "expected_result": {
                "audit_result": "REVIEW",
                "reason_keywords": ["敏感词"]
            }
        },
        {
            "description": "低质量内容测试",
            "post_id": 1005,
            "title": "测试",
            "content": "测试一下",
            "user_id": 5,
            "expected_result": {
                "reason_keywords": ["质量"]
            }
        }
    ]

def get_feedback_data() -> Dict[str, Any]:
    """获取反馈测试数据"""
    return {
        "post_id": 1002,
        "admin_id": 999,
        "ai_decision": "REJECT",
        "final_decision": "REJECT",
        "is_correct": True,
        "feedback": "AI正确识别了垃圾广告内容"
    }

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="自动审核服务API测试脚本")
    parser.add_argument("--url", default="http://localhost:8090", help="API基础URL")
    args = parser.parse_args()
    
    # 创建测试工具
    tester = AuditServiceTester(args.url)
    
    # 测试健康检查
    if not tester.check_health():
        logger.error("健康检查失败，服务可能不可用")
        sys.exit(1)
    
    # 测试审核API
    test_cases = get_test_cases()
    audit_test_passed = tester.test_audit_api(test_cases)
    
    # 测试反馈API
    feedback_data = get_feedback_data()
    feedback_test_passed = tester.test_feedback_api(feedback_data)
    
    # 输出测试结果
    logger.info("\n========== 测试结果汇总 ==========")
    logger.info(f"审核API测试: {'通过 ✓' if audit_test_passed else '失败 ✗'}")
    logger.info(f"反馈API测试: {'通过 ✓' if feedback_test_passed else '失败 ✗'}")
    logger.info("=================================")
    
    # 设置退出码
    sys.exit(0 if audit_test_passed and feedback_test_passed else 1)

if __name__ == "__main__":
    main() 